package com.blog.boot.beetl.config;

import org.beetl.core.GroupTemplate;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.ext.spring.BeetlSpringViewResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cailong
 * @ClassName: BeetlConfig
 * @Description: 创建Beetl配置类
 * @date 2018/11/29
 */
@Configuration
public class BeetlConfig {

    //模板根目录 ，比如 "templates"
    @Value("${beetl.templatesPath}") String templatesPath;

    /*@Value("${beetl.templatesPathDev}") String templatesPathDev;*/

    /*@Value("${islocal}") Boolean islocal;*/

    @Bean
    public GroupTemplate getGroupTemplate(BeetlGroupUtilConfiguration beetlGroupUtilConfiguration) {
        GroupTemplate gt = beetlGroupUtilConfiguration.getGroupTemplate();
        Map<String,Object> shared = new HashMap<>();
        shared.put("title_suffix","博客");
        gt.setSharedVars(shared);
        return gt;
    }


    @Bean
    public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {
        BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
        /*if(islocal){//如果是本地开发 那么就用类加载器*/
            //获取Spring Boot 的ClassLoader
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            if(loader==null){
                loader = BeetlConfig.class.getClassLoader();
            }
            ClasspathResourceLoader cploder = new ClasspathResourceLoader(loader,
                    templatesPath);
            beetlGroupUtilConfiguration.setResourceLoader(cploder);
            beetlGroupUtilConfiguration.init();
            //如果使用了优化编译器，涉及到字节码操作，需要添加ClassLoader
            beetlGroupUtilConfiguration.getGroupTemplate().setClassLoader(loader);
       /* }else{
            beetlGroupUtilConfiguration.setResourceLoader(new FileResourceLoader(templatesPath+ File.separator));
            beetlGroupUtilConfiguration.init();
            System.out.println("生产环境“外部加载”");
        }*/
        return beetlGroupUtilConfiguration;

    }

    @Bean(name = "beetlViewResolver")
    public BeetlSpringViewResolver getBeetlSpringViewResolver(BeetlGroupUtilConfiguration beetlGroupUtilConfiguration) {
        BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver();
        beetlSpringViewResolver.setContentType("text/html;charset=UTF-8");
        beetlSpringViewResolver.setOrder(0);
        beetlSpringViewResolver.setConfig(beetlGroupUtilConfiguration);
        System.out.println("beetl Startup success");
        return beetlSpringViewResolver;
    }
}
